package com.hankol.message.view

import android.app.Activity
import android.content.Context
import android.os.Handler
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.baselibrary.BaseConstant
import com.baselibrary.MessageBus
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.extension.load
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.hankol.message.HtmlUtil
import com.hankol.message.R
import com.hankol.message.adapter.BroadcastMsgListAdapter
import com.hankol.message.bean.GetSysMsgListBean
import com.hankol.message.bean.UnReadCntBean
import com.meiqia.core.MQManager
import com.meiqia.core.bean.MQMessage
import com.meiqia.core.callback.OnGetMessageListCallback
import java.util.*

/**消息 顶部
 * @date: 2022/2/28
 * @Des：
 */
class HomeMsgHeadView : LinearLayout, View.OnClickListener {

    private lateinit var tvLikeAndCollect: TextView
    private lateinit var tvMsgCommentMe: TextView
    private lateinit var tvMsgNewFans: TextView
    private lateinit var tvTime: TextView
    private lateinit var rvSystem: RecyclerView
    //客服消息红点
    private lateinit var tvRedDotKf: TextView
    private lateinit var imgHeardKf: ImageView
    private lateinit var act: Activity
    //消息首页的广播列表
    private val systemListAdapter by lazy { BroadcastMsgListAdapter() }

    constructor(context: Context) : super(context) {
        initView()
    }

    constructor(context: Context, act: Activity) : super(context) {
        this.act = act
        initView()
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        initView()
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        initView()
    }


    private fun initView() {
        LayoutInflater.from(context).inflate(R.layout.heard_top_chat, this)
        findViewById<RelativeLayout>(R.id.rl_customer_service).setOnClickListener(this)
        tvLikeAndCollect = findViewById<TextView>(R.id.tv_msg_like_and_collect)
        tvMsgCommentMe = findViewById<TextView>(R.id.tv_msg_comment_me)
        tvMsgNewFans = findViewById<TextView>(R.id.tv_msg_new_fans)
        tvRedDotKf = findViewById<TextView>(R.id.tv_red_dot_kf)
        imgHeardKf = findViewById<ImageView>(R.id.img_heard_kf)
        tvTime = findViewById<TextView>(R.id.tv_time)
        getMeiQiaNoReadCnt(false)

        tvLikeAndCollect.setOnClickListener(this)
        tvMsgCommentMe.setOnClickListener(this)
        tvMsgNewFans.setOnClickListener(this)
        if (MQManager.getInstance(ContextUtils.getCurApplication().getApplicationContext()).getCurrentAgent().checkNotNull()) {
            if (MQManager.getInstance(ContextUtils.getCurApplication().getApplicationContext()).getCurrentAgent().avatar.checkNotNull()) {
                imgHeardKf.load(imgHeardKf.context, MQManager.getInstance(ContextUtils.getCurApplication().getApplicationContext()).getCurrentAgent().avatar.checkValue())
            } else {
                imgHeardKf.setImageResource(R.drawable.ic_msg_kf)
            }
        } else {
            imgHeardKf.setImageResource(R.drawable.ic_msg_kf)
        }
        if (!SpUtils.getInstance().userAgreePrivacy) {
            // 如果是第一次启动
            setCostumServerMsg(1)
        }
        rvSystem = findViewById<RecyclerView>(R.id.rv_system)
        rvSystem.adapter = systemListAdapter
        systemListAdapter.setOnItemClickListener { adapter, view, position ->
            if (!DoubleClickHelper.isOnDoubleClick()) {
                SensorsDataManager.instance.brookPageElementClick("系统消息")
                val bean = adapter.data[position] as GetSysMsgListBean
                if (bean.unreadCount > 0) {
                    SensorsDataManager.instance.messageReminder("系统消息")
                }
                //进详情  广播 列表
                val hashMap = HashMap<String, Any>()
                hashMap["msgPushTypeId"] = bean.msgPushTypeId
                hashMap["title"] = bean.name
                ARouterUtils.jump(ActivityRouter.MESSAGE.SYSTEM_MESSAGE_LIST, hashMap)
            }
        }
    }

    //美洽 未读消息
    fun getMeiQiaNoReadCnt(isDelay: Boolean) {
        Handler().postDelayed({
            //这里执行相应的代码，UI线程
            MQManager.getInstance(context).getUnreadMessages(object : OnGetMessageListCallback {
                override fun onSuccess(list: List<MQMessage>) {
                    val noReadCnt = list.size
                    setCostumServerMsg(noReadCnt)
                    if (noReadCnt <= 0) {
                        //                        val builder = MessageBus.Builder()
                        //                        val messageBus = builder.codeType(MessageBus.msgId_hide_meiqia_red_dot).build()
                        //                        EventBus.getDefault().post(messageBus)
                    }
                }

                override fun onFailure(i: Int, s: String) {

                }
            })
        }, (if (isDelay) 3000 else 0).toLong())
    }

    //客服未读消息数量
    private fun setCostumServerMsg(msgCnt: Int) {
        tvRedDotKf.visibility = if (msgCnt > 0) View.VISIBLE else View.GONE
        tvRedDotKf.text = "${msgCnt}"
        EventBusUtils.sendNotify(MessageBus.msgId_hide_meiqia_red_dot)
    }

    var unReadbean: UnReadCntBean? = null
    //刷新顶部数量
    fun setTopCnt(bean: UnReadCntBean) {
        unReadbean = bean
        //赞和收藏，未读数量
        val tvRedDotLike = findViewById<TextView>(R.id.tv_red_dot_like)
        //评论我的，未读数量
        val tvRedDotCommentMe = findViewById<TextView>(R.id.tv_red_dot_comment_me)
        //新增粉丝，未读数量
        val tvRedDotNewFans = findViewById<TextView>(R.id.tv_red_dot_like_new_fans)
        bean.apply {
            tvRedDotLike.visibility = if (supportAndFavorite > 0) View.VISIBLE else View.GONE
            tvRedDotCommentMe.visibility = if (commentOnMy > 0) View.VISIBLE else View.GONE
            tvRedDotNewFans.visibility = if (newFans > 0) View.VISIBLE else View.GONE

            CommonUtil.formatNum99(tvRedDotLike,supportAndFavorite)
            CommonUtil.formatNum99(tvRedDotCommentMe,commentOnMy)
            CommonUtil.formatNum99(tvRedDotNewFans,newFans)
        }
        //默认显示
        setLastMessage()
        EventBusUtils.sendNotify(MessageBus.msgId_refresh_un_read_msg_cnt)
    }

    //广播列表赋值
    fun setSystemListData(dataList: List<GetSysMsgListBean>) {
        if (dataList.checkNotNull() && dataList.size > 0) {
            rvSystem.visibility = View.VISIBLE
            systemListAdapter.setNewData(dataList)
        } else {
            rvSystem.visibility = View.GONE
        }
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.tv_msg_like_and_collect -> { //点赞和收藏列表
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    unReadbean?.let {
                        if (it.supportAndFavorite > 0)
                            SensorsDataManager.instance.messageReminder("赞和收藏")
                    }
                    SensorsDataManager.instance.brookPageElementClick("赞和收藏")
                    ARouterUtils.jump(ActivityRouter.MESSAGE.LIKE_AND_COLLECT)
                }
            }
            R.id.tv_msg_comment_me -> { //评论我的列表
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    unReadbean?.let {
                        if (it.commentOnMy > 0)
                            SensorsDataManager.instance.messageReminder("评论我的")
                    }
                    SensorsDataManager.instance.brookPageElementClick("评论我的")
                    ARouterUtils.jump(ActivityRouter.MESSAGE.COMMENT_ME)
                }
            }
            R.id.tv_msg_new_fans -> { //新增粉丝 列表
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    unReadbean?.let {
                        if (it.newFans > 0)
                            SensorsDataManager.instance.messageReminder("新增粉丝")
                    }
                    SensorsDataManager.instance.brookPageElementClick("新增粉丝")
                    val map2 = HashMap<String, Any>()
                    map2[BaseConstant.ATTENIVE_INDEX] = 1
                    ARouterUtils.jump(ActivityRouter.MINE_CENTER.MINE_ATTENTIVE, map2)
                }
            }
            R.id.rl_customer_service -> {
                if (tvRedDotKf.text.checkNotNull()) {
                    SensorsDataManager.instance.messageReminder("在线客服")
                }
                SensorsDataManager.instance.brookPageElementClick("在线客服")
                //客服
                CommonUtil.openCustomerService(act)
                setCostumServerMsg(0)
            }
        }
    }

    //设置美洽最后一条消息内容
    fun setLastMessage() {
        val tvCoServerContent = findViewById<TextView>(R.id.tv_co_server_content)
        val mManager = MQManager.getInstance(ContextUtils.getCurApplication().applicationContext)
        mManager.getMQMessageFromService(System.currentTimeMillis(), 10, object : OnGetMessageListCallback {
            override fun onSuccess(p0: MutableList<MQMessage>?) {
                if (p0.checkNotNull()) {
                    p0?.let {
                        val mqMessage = it[p0.size - 1]
                        val lastMessage = HtmlUtil.Html2Txt(mqMessage.content.checkValue())
                        tvCoServerContent.text = if (lastMessage.checkNotNull()) lastMessage else "Hi～我是在线客服小酣，这里反馈问题"
                        val lastMessageTime = mqMessage.created_on
                        tvTime.text = "${TimeUtil.fromToday(lastMessageTime)}"
                        tvTime.visibility = if (lastMessageTime == 0L) View.GONE else View.VISIBLE
                        if (mqMessage.from_type == MQMessage.TYPE_FROM_AGENT) {
                            if (!act.isDestroyed) {
                                imgHeardKf.load(act, mqMessage.avatar.checkValue())
                            }
                        } else {
                            imgHeardKf.setImageResource(R.drawable.ic_msg_kf)
                        }
                    }
                } else {
                    tvCoServerContent.text = "Hi～我是在线客服小酣，这里反馈问题"
                    tvTime.visibility = View.GONE
                }
            }

            override fun onFailure(p0: Int, p1: String?) {
            }
        })
    }
}
